package com.company.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;

public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            // 加载MyBatis配置文件（确保路径正确）
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            // 初始化失败时抛出异常，避免后续NullPointerException
            throw new ExceptionInInitializerError("MyBatis配置文件加载失败：" + e.getMessage());
        }
    }

    public static SqlSession getSqlSession() {
        if (sqlSessionFactory == null) {
            throw new IllegalStateException("MyBatis未初始化，请检查配置文件");
        }
        return sqlSessionFactory.openSession(true); // 自动提交事务
    }

    public static void closeSqlSession(SqlSession session) {
        if (session != null) {
            session.close();
        }
    }
}